/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.tukano.misc;

import it.tukano.lang.StringExt;
import it.tukano.swingdeco.containers.JFrameExt;
import it.tukano.swingdeco.containers.JPanelExt;
import it.tukano.swingdeco.controls.JButtonExt;
import it.tukano.swingdeco.input.PopupInput;
import it.tukano.swingdeco.text.DigitsDocument;
import it.tukano.swingdeco.text.JTextFieldExt;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.Point;
import javax.swing.JPopupMenu;

/**
 * Term editor
 * @author utente4
 */
public class TermEditor {
    private final JTextFieldExt years = new JTextFieldExt(5)
            .withDocument(new DigitsDocument());
    private final JTextFieldExt months = new JTextFieldExt(5)
            .withDocument(new DigitsDocument());
    private final JTextFieldExt weeks = new JTextFieldExt(5)
            .withDocument(new DigitsDocument());
    private final JTextFieldExt days = new JTextFieldExt(5)
            .withDocument(new DigitsDocument());
    private final JPanelExt grid = new JPanelExt(new GridLayout(4, 1, 4, 4))
            .appendWithTitles("Anni", years, "Mesi", months, "Settimane", weeks, "Giorni", days);
    
    public Term getEditorValue() {
        int y = StringExt.wrap(years).toInteger(0);
        int m = StringExt.wrap(months).toInteger(0);
        int w = StringExt.wrap(weeks).toInteger(0);
        int d = StringExt.wrap(days).toInteger(0);
        return new Term(y, m, w, d);
    }
    
    public void setEditorValue(Term t) {
        if(t == null) {
            years.setText("");
            months.setText("");
            days.setText("");
            weeks.setText("");
        } else {
            years.setText(t.getYears());
            months.setText(t.getMonths());
            days.setText(t.getDays());
            weeks.setText(t.getWeeks());
        }
    }
    
    public JPopupMenu popup(Component parent, Point locationOnParent, Runnable onAccept, Runnable onCancel) {
        return PopupInput.showConfirmPopup("Durata", parent, grid, locationOnParent, onAccept, onCancel);
    }
    
    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            
            public void run() {
                final JButtonExt pop = new JButtonExt("test");
                final TermEditor ed = new TermEditor();
                final JFrameExt f = new JFrameExt().defaultDispose();
                f.add(pop.onAction(new Runnable() {

                    public void run() {
                        ed.popup(pop, new Point(0, 0), new Runnable() {

                            public void run() {
                                System.out.println("->" + ed.getEditorValue());
                            }
                        }, null);
                    }
                }));
                f.displayOnScreen();
            }
        });
    }
}
